var config = require('./config.json')
var express = require('express')
var router = express.Router()
var request = require('request')
var remoteHost = 'http://localhost:' + config.api_port
var muilter = require('./multerUtil')
var upload = muilter.single('file')
var fs = require('fs')
var path = require('path')

router.all('/service/cs/upload/attachment/download1', (req, res) => {
  console.log(req.body)
  var filePath = path.join(__dirname, '../single.xlsx')
  var stats = fs.statSync(filePath)
  if (stats.isFile()) {
    res.set({
      'Content-Type': 'application/octet-stream',
      'Content-Disposition': 'attachment;fileName=case_org:1511763970698',
      'Content-Length': stats.size
    })
    fs.createReadStream(filePath).pipe(res)
  } else {
    res.end(404)
  }
})

router.all('/service/cs/upload/attachment/download2', (req, res) => {
  console.log(req.body)
  res.set({
    'Content-Type': 'application/octet-stream',
    'Content-disposition': 'attachment;filename=a.text',
    'Content-Length': '123',
  })
  return res.sendFile(path.join(__dirname, '../single.xlsx'))
})


router.all('/service/*', upload, function (req, res) {
  var data = req.body
  var type = req.get('Content-Type')
  var otps = {
    method: req.method,
    url: remoteHost + req.path,
    query: req.query,
    headers: {
      'Content-Type': req.get('Content-Type'),
      'content-length': req.get('Content-length')
    }
  }
  // otps.headers = req.headers
  if (data) {
    if (type) {
      if (type.indexOf('form') >= 0) {
        otps.formData = JSON.parse(JSON.stringify(data))
      } else if (type.indexOf('json') >= 0) {
        otps.body = data
        otps.json = true
      }
    } else {
      otps.body = data
      otps.json = true
    }
  }

  if (req.query) {
    var f = ''
    for (let i in req.query) {
      f += i + '=' + req.query[i] + '&'
    }
    if (f !== '') {
      f = f.slice(0, -1)
      otps.url += '?' + f
    }
  }
  if (otps.formData && req.file) {
    otps.formData[req.file.fieldname] = fs.createReadStream(req.file.path)
  }
  if (otps.formData) {
    otps = {
      formData: otps.formData,
      url: otps.url,
      headers: {
        'Content-Type': req.get('Content-Type')
      }
    }
  }
  request(otps, function (error, response, body) {
    if (error) {
      console.error('API ERROR:' + error)
    }
    res.send(body)
  })
})
module.exports = router
